import { is2DArray } from '../utils'
import type {
  EchartsOptions,
  DataType,
  DataItem,
  ChartsConfig,
  SeriesOption,
} from '../types/charts'
import { createXAxis, createYAxis, createGrid } from './createCommon'

const createBarOption = (chartOptions: EchartsOptions, options: ChartsConfig, data: DataType) => {
  const xAxis = createXAxis(options, data)
  if (Object.keys(xAxis).length > 0) {
    chartOptions.xAxis = xAxis
  }

  const yAxis = createYAxis(options)
  if (Object.keys(yAxis).length > 0) {
    chartOptions.yAxis = yAxis
  }

  const grid = createGrid(options)
  if (Object.keys(grid).length > 0) {
    chartOptions.grid = grid
  }

  const series = createSeries(options, data)
  if (series.length > 0) {
    chartOptions.series = series as SeriesOption[]
  }
  return chartOptions
}

// 生成series部分
const createSeries = (options: ChartsConfig, data: DataType) => {
  let series = []
  let values = []
  const opt = (options.series as SeriesOption) || {}
  if (is2DArray(data)) {
    values = data.map((item: DataItem[]) => item.map((subItem: DataItem) => subItem.value))
  } else {
    values = [data.map((item: DataItem) => item.value)]
  }
  series = values.map((value) => {
    const seriesItem = {
      type: 'bar',
      data: value,
      showBackground: opt.background ? true : false,
      backgroundStyle: {
        color: opt.background || 'rgba(180, 180, 180, 0.2)',
      },
    }
    return seriesItem
  })
  return series
}
export default createBarOption
